package faf.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import faf.business.UserManager;
import faf.entities.Account;
import faf.web.data.NewAccountForm;

public class CreateAccountController extends SimpleFormController {

	UserManager userManager;

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		NewAccountForm form = (NewAccountForm) command;

		Account account = new Account();
		account.setMail(form.getEmail());
		account.setPassword(form.getPassword());
		account.setFirstname(form.getFirstname());
		account.setLastname(form.getLastname());
		
		account = userManager.createAccount(account);

		if (account == null) { // account creation failed there is someone with
								// same email
			errors.rejectValue("email", "email-conflict");
			return showForm(request, response, errors);
		} else {
			request.getSession().setAttribute("user", account);
			return new ModelAndView(new RedirectView(getSuccessView()));
		}
	}
}
